package cate.game.activity.dailygift;

import cate.common.table.activity.dailygift.DailyGiftAllInRow;
import cate.common.table.activity.dailygift.DailyGiftConfigRow;
import cate.common.table.activity.dailygift.DailyGiftFreeRewardRow;
import cate.common.table.activity.dailygift.DailyGiftWishRow;
import cate.common.table.d.GDDailyGift;
import cate.common.table.d.GDObj;
import cate.common.table.d.GDOperation;
import cate.common.table.pay.PayItemRow;
import cate.common.util.GameResult;
import cate.game.activity.base.core.RoleActivitySingle;
import cate.game.activity.dailygift.msg.DailyGiftDataResp;
import cate.game.event.activity.BuyGiftEvent;
import cate.game.res.MixRes;
import cate.game.res.MixResItem;
import cate.game.role.Role;
import com.fasterxml.jackson.annotation.JsonIgnore;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;
import org.apache.commons.lang3.StringUtils;

import java.beans.Transient;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@NoteClass(value = "每日特惠")
public class DailyGiftActivity extends RoleActivitySingle {
    @NoteField(value = "自选英雄碎片ID")
    public int wishFragID;

    @NoteField(value = "礼包", detail = "<礼包id(不包含免费礼包),是否购买过>")
    public Map<Integer, Boolean> map;

    @NoteField(value = "免费礼包购买")
    public boolean freeGift;

    @Override
    public void initialize(Role role) {
        super.initialize(role);
        if (map == null) {
            map = new HashMap<>();
        }
        if (GDDailyGift.MODE_FRAGMENT) {
            wishFragID = GDDailyGift.FREE_FRAG_ID;
        }
    }

    @Override
    public void onEnter() {
        super.onEnter();
        if (GDDailyGift.MODE_FRAGMENT) {
            wishFragID = GDDailyGift.FREE_FRAG_ID;
        }
    }

    @Override
    public void excelCheck() {
        List<DailyGiftConfigRow> giftRowList = role.getGame().table.dailyGift.config.getConfig(configTid());

        for (DailyGiftConfigRow row : giftRowList) {
            if (row.price != 0 && !map.containsKey(row.id)) {
                map.put(row.id, false);
            }
        }
    }

    @Override
    public void onRoleOpen() {

    }

    @Override
    public void onRoleEnd() {
        map.clear();
        freeGift = false;
    }

    @Override
    public void initSend() {
        noticeUpdate();
    }

    public void noticeUpdate() {
        role.sendNow(new DailyGiftDataResp(this));
    }

    public void setWishFragment(int wishID) {
        if (GDDailyGift.MODE_FRAGMENT) {
            return;
        }

        List<DailyGiftWishRow> list = getWishRowList();
        if (list == null || list.stream().noneMatch(row -> row.fragment == wishID)) {
            role.getGame().notice.message(role, "尝试选择不存在的英雄碎片");
            return;
        }
        wishFragID = wishID;
        noticeUpdate();
    }

    /**
     * 购买成功
     */
    public void onPaySuccess(PayItemRow pir) {
        int id = pir.funcSubId;
        DailyGiftConfigRow configRow = getConfigRow(id);
        List<DailyGiftConfigRow> list = new LinkedList<>();
        if (configRow != null) {
            list.add(configRow);
        }
        if (list.isEmpty()) {
            role.getGame().notice.message(role, "礼包不存在");
            return;
        }
        sendGiftList(list);
        noticeUpdate();
//        for (boolean flag :
//                map.values()) {
//            if (!flag) {
//                return;
//            }
//        }
//        publishEvent(role, new BuyGiftEvent(role, base.funcId, 1));
    }

    /**
     * 购买成功
     */
    public void onPaySuccessOneKey(PayItemRow pir) {
        if (map.entrySet().stream().filter(entry -> getConfigRow(entry.getKey()).confId == configTid()).anyMatch(Map.Entry::getValue)) {
            role.getGame().notice.message(role, "部分礼包已售罄");
            return;
        }
        List<DailyGiftConfigRow> list = new LinkedList<>(getAllPayItemRow());
        sendGiftList(list);
        noticeUpdate();
//        publishEvent(role, new BuyGiftEvent(role, base.funcId, 1));
    }


    /**
     * 获取所有可选碎片
     */
    @JsonIgnore
    @Transient
    private List<DailyGiftWishRow> getWishRowList() {
        return role.getGame().table.dailyGift.wish.getList();
    }

    /**
     * 获取所有礼包配置
     */
    @JsonIgnore
    @Transient
    private List<DailyGiftConfigRow> getAllPayItemRow() {
        List<DailyGiftConfigRow> list = role.getGame().table.dailyGift.config.getConfig(configTid());
        list.removeIf(e -> e.price == 0);
        return list;
    }

    /**
     * 发送所有礼包内容
     */
    private void sendGiftList(List<DailyGiftConfigRow> list) {
        MixRes res = new MixRes();

        list.forEach(row -> res.addList(sendGiftItem(row)));
        role.log.setOperation(GDOperation.ACT_DAILY_GIFT);

        res.add(role, true, GDOperation.ACT_DAILY_GIFT);
        role.log.clearOperation();
        role.getGame().notice.dialogReward(role, res);
    }

    /**
     * 发单个礼包
     */
    private MixRes sendGiftItem(DailyGiftConfigRow row) {
        MixRes res = new MixRes(row.giftStr);
        if (row.price == 0) {
            freeGift = true;
            return res;
        }

//        int num = row.randomList.get().num;

//        res.addItem(new MixResItem(GDObj.Type.HERO_PART, wishFragID, num));

        if (map.containsKey(row.id)) {
            map.put(row.id, true);
        }
        return res;
    }

    /**
     * 获取单个礼包配置
     */
    @JsonIgnore
    @Transient
    protected DailyGiftConfigRow getConfigRow(int id) {
        return role.getGame().table.dailyGift.config.getRowByItemId(id, configTid());
    }

    /**
     * 获取一键购买配置
     */
    @JsonIgnore
    @Transient
    protected DailyGiftAllInRow getAllInRow() {
        return role.getGame().table.dailyGift.allIn.get(configTid());
    }

    /**
     * 是否允许购买
     *
     * @param pir 配置ID
     * @return 检测结果 无携带数据
     */
    public GameResult<Void> allowPay(PayItemRow pir) {
        int id = pir.funcSubId;
        GameResult<Void> r = new GameResult<>();
        DailyGiftConfigRow configRow = getConfigRow(id);
        if (configRow == null) {
            role.getGame().notice.message(role, "尝试购买不存在的礼包");
            return r.fail("尝试购买不存在的礼包");
        }
        if ((configRow.price == 0 & freeGift) || (map.get(id) != null && map.get(id))) {
            role.getGame().notice.message(role, "已售罄");
            return r.fail("已售罄");
        }
        if (role.getBase().vip < configRow.vip) {
            return r.fail("vip等级不足");
        }
        return r.success();
    }

    /**
     * 是否允许一键购买
     *
     * @param pir 配置ID
     * @return 检测结果 无携带数据
     */
    public GameResult<Void> allowPayOneKey(PayItemRow pir) {
        GameResult<Void> r = new GameResult<>();
        DailyGiftAllInRow allInRow = getAllInRow();
        if (allInRow == null) {
            role.getGame().notice.message(role, "尝试购买不存在的礼包");
            return r.fail("尝试购买不存在的礼包");
        }
        if (map.entrySet().stream().filter(entry -> getConfigRow(entry.getKey()).confId == configTid()).anyMatch(Map.Entry::getValue)) {
            role.getGame().notice.message(role, "部分礼包已售罄");
            return r.fail("部分礼包已售罄");
        }
        if (role.getBase().vip < allInRow.vip) {
            return r.fail("vip等级不足");
        }
        return r.success();
    }

    @Override
    public void onDaySpan(boolean silence) {
        super.onDaySpan(silence);
        map.replaceAll((k, v) -> false);
        freeGift = false;
        noticeUpdate();
    }

    public GameResult<DailyGiftActivity> takeFreeGift() {
        GameResult<DailyGiftActivity> r = new GameResult<>();
        r.data = this;
        DailyGiftFreeRewardRow row = role.getGame().table.dailyGift.freeReward.getRowByVip(role.getBase().vip);
        if (row == null) {
            return r.fail("找不到对应奖励");
        }
        if (StringUtils.isBlank(row.reward)) {
            return r.fail("奖励未配置");
        }
        if (freeGift) {
            return r.fail("奖励已领取");
        }
        MixRes rew = new MixRes(row.reward);
        rew.add(role, true, GDOperation.ACT_DAILY_GIFT_FREE, row.id);
        role.getGame().notice.dialogReward(role, rew);
        freeGift = true;
        return r;
    }
}
